#!/bin/bash

# 文档说明
# 用于正式环境Jenkins发布使用
# 参数：
#  - $1, UPLOAD_DIR 应用上传目录

set -x

source /etc/profile

#e:/home/www/product_history/cs/codrim-cs-crawler/
UPLOAD_DIR=$1 
#e:/home/www/product/cs/codrim-cs-crawler/
RUN_DIR=$2
APP=$3
JMX_REMOTE_PORT=$4
RUN_PORT=$5
if [ ! -d "${UPLOAD_DIR}" ]; then
	mkdir -p "${UPLOAD_DIR}tmp_upload"
	echo 'crate upload dir success,dir is:'${UPLOAD_DIR}
fi

if [ ! -d "${RUN_DIR}" ]; then
	mkdir -p $RUN_DIR
	echo 'crate run dir success,dir is:'${RUN_DIR}
fi

echo $APP
PSEF=` ps -ef | grep ${APP} | grep 'jar'`

if [ -n  "${PSEF}" ]; then
        echo 'bak project starting...'
	BAK_DIR=${UPLOAD_DIR}`date +%Y%m%d%H%M`
        mkdir -p "${UPLOAD_DIR}`date +%Y%m%d%H%M`"
        mv ${RUN_DIR}*.jar ${BAK_DIR}/
        echo 'bak project success.bak dir:'"${BAK_DIR}"

        PID=`echo ${PSEF}| awk '{print $2}' | sed -n '1p'`
        kill -9 $PID
        echo 'kill old project by pid, pid:'$PID
fi


echo 'PSEF'
UPLOAD_FILE=${UPLOAD_DIR}tmp_upload/${APP}-[0-9]*.jar
chmod 755 $UPLOAD_FILE
mv ${UPLOAD_FILE} ${RUN_DIR}
echo 'move upload file to run dir success,file:'${UPLOAD_FILE}',run dir:'${RUN_DIR}
APP=${RUN_DIR}${APP}-[0-9]*.jar

if [ ! -d "${JAVA_HOME}" ]; then
        echo "JAVA_HOME not exists"
        exit -1
fi
JAVA="${JAVA_HOME}/bin/java"

if [ "$JMX_REMOTE_PORT" -eq "-1" ]; then
        cmd="nohup $JAVA -jar ${APP} --spring.profiles.active=prod"
else
        cmd="nohup $JAVA -Dcom.sun.management.jmxremote.port=${JMX_REMOTE_PORT}"
        cmd="${cmd} -Dcom.sun.management.jmxremote.ssl=false "
        cmd="${cmd} -Dcom.sun.management.jmxremote.authenticate=false "
        cmd="${cmd} -Dcom.sun.management.jmxremote.local.only=false"
        cmd="${cmd} -Djava.rmi.server.hostname=47.88.191.88 -jar ${APP}"
        cmd="${cmd} --spring.profiles.active=prod"
fi

if [ $# == 5 ]; then
        cmd="${cmd} --server.port=$5"
fi

cmd="${cmd} > ${RUN_DIR}$3.log 2>&1 &"
eval $cmd
echo 'execute cmd:' ${cmd}
